<?php

class Authorization
{
	private $format = "JSON";
	private $charset = "UTF-8";
	private $fileCharset = "UTF-8";
	private $appId = "2017022705914642";  //开发id
	private $postCharset = "UTF-8";  // 表单提交字符集编码
	private $rsaPrivateKeyFilePath;  //私钥文件路径
	public  $gatewayUrl = "https://openapi.alipay.com/gateway.do";
	private $rsaPrivateKey = 'MIICXgIBAAKBgQDEij4a68AElmGASGfpw2Pwl8ez23kXP3g1f67iwxqpk3lrNBYoQAut6GoxlCnJKr/42cVPzTWqacYHl1spEvDFbH6G9FVAJM8qMgpjcJ5yt3iIBSv2jn6AEzL6mnY/Q4iu8EFRp4gVDgs269KK5uk3rx8liBGdlDYx4RAkNTzhuwIDAQABAoGBAI4yVuyzVKH9C139BPGkZFJV/i6qw9mGGjravnViI5A9GsPtU3qbm9efJ/Xm9LSPMYWiSZeLKSC6loQ3hcUZ5wgq9/0GIv/q9P2qHyX07Zo9HPRcSHjhZnY4UJhSKI5boy/wcyHCBsf7QrvprNsEa6mL+46r89dmCosD4/ch7DjBAkEA4ibPoweziVdkwBHRl5pO5T5PvbFAHQh7grP0oDOsvw8DLEHxfFqp+9hASCVWQYQCmFr/ggtSCY55yHkpNtfK1wJBAN566vE+UBspHW60oMUr97UTukftqY/UIrgcHB7Lv3U4WFeGgxVRu2XC4lvB6Z1IR5O8nmcbZeDxUBkG9h/Zx70CQELxyjUwam0VebWBkNGX1BL4RxKYDaqKgEVIj/l8Un6cKwxG2P0+uWLbuOuiYc4zDbGb/la4kyhRDKvTcefSKTECQQCUtZihFEO7Q+o2e2oTIWZ7lOoo9gUm7GcgpTlupEYfdkAmkPTBpVYbmP5w0tbymMOvTp6a0MdyahpeADc35vwJAkEAm/yV3nN3flD/X3qCt2bIlbFw2vwHdKhRaBy/G6v1Ug/fO0OTvWMj1mysHNA/MkphjA9RXUp9MqUC8Vi+YlYvJw=='; //请填写开发者私钥去头去尾去回车，一行字符串

	public function getAutoParams()
	{
		$param = array(
			'app_id' => $this->appId,
			'format' => $this->format,
			'charset' => $this->charset,
			'sign_type' => "RSA",
			'timestamp' => date('Y-m-d H:i:s'),
			'version' => "1.0",
			'grant_type' => "authorization_code"
		);
		return $param;
	}
	
	/**
	 * @param $url
	 * @param $postBodyString
	 * @return mixed
	 */
	public function curl($postData) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->gatewayUrl);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
		$reponse = curl_exec($ch);
		curl_close($ch);
		return $this->codedConversion($reponse);
	}
	
	 /**
	 * 生成sign
	 * @param unknown $params
	 * @param string $signType
	 */
	public function generateSign($params, $signType = "RSA") {
	    return $this->sign($this->getSignContent($params), $signType);
	}
	
	protected function sign($data, $signType = "RSA") {
	    if($this->checkEmpty($this->rsaPrivateKeyFilePath)){
	        $priKey=$this->rsaPrivateKey;
	        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
	                wordwrap($priKey, 64, "\n", true) .
	                "\n-----END RSA PRIVATE KEY-----";
	    }else {
	        $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
	        $res = openssl_get_privatekey($priKey);
	    }
	
	    ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
	
	    if ("RSA2" == $signType) {
	        openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
	    } else {
	        openssl_sign($data, $sign, $res);
	    }
	
	    if(!$this->checkEmpty($this->rsaPrivateKeyFilePath)){
	        openssl_free_key($res);
	    }
	    $sign = base64_encode($sign);
	    return $sign;
	}
	
	/**
	 * 
	 * @param unknown $params
	 * @return string
	 */
	public function getSignContent($params) {
	    
	    ksort($params);
	    $stringToBeSigned = "";
	    $i = 0;
	    foreach ($params as $k => $v) {
	        if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
	
	            // 转换成目标字符集
	            // $v = $this->characet($v, $this->postCharset);
	
	            if ($i == 0) {
	                $stringToBeSigned .= "$k" . "=" . "$v";
	            } else {
	                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
	            }
	            $i++;
	        }
	    }
	    unset ($k, $v);
	    return $stringToBeSigned;
	}
	
	/**
	 * 校验$value是否非空
	 *  if not set ,return true;
	 *    if is null , return true;
	 **/
	protected function checkEmpty($value) {
	    if (!isset($value))
	        return true;
	    if ($value === null)
	        return true;
	    if (trim($value) === "")
	        return true;
	
	    return false;
	}
	
	/**
	 * 转换字符集编码
	 * @param $data
	 * @param $targetCharset
	 * @return string
	 */
	function characet($data, $targetCharset) {
	
	    if (!empty($data)) {
	        $fileType = $this->fileCharset;
	        if (strcasecmp($fileType, $targetCharset) != 0) {
	            $data = mb_convert_encoding($data, $targetCharset, $fileType);
	        }
	    }
	    return $data;
	}

	public function getAppid()
	{
		return $this->appId;
	}

	/**
	 * 将非utf8 转换成utf8
	 */
	private function codedConversion($data)
	{
		$encode = mb_detect_encoding($data, array("GB2312","GBK",'BIG5', 'UTF-8'));
		if ($encode != 'UTF-8') {
			$data = mb_convert_encoding($data, 'UTF-8', $encode); 
		}

        return $data;
	}
}